package com.changgou.web.gateway.filter;

import com.changgou.web.gateway.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String LOGIN_URL="http://localhost:8001/api/oauth/toLogin";

    @Autowired
    private AuthService authService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        //如果请求的是登录请求 ， 则直接放行
        if ("/api/oauth/login".equals(path) || !UrlFilter.hasAuthorize(path)){
            return chain.filter(exchange);
        }

        //获取cookie中的jti的值，如果不存在，则不放行

        String jti = authService.getJtiFromCookie(request);
        if (jti.isEmpty()){
            //response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //return response.setComplete();
            //跳转登录页面
            return this.toLoginPage(LOGIN_URL,exchange);
        }
        //根据jti获取redis中的jwt的值，如果不存在，则拒绝访问
        String jwt = authService.getJwtFromJti(jti);
        if (StringUtils.isEmpty(jwt)){
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
            //跳转登录页面
            return this.toLoginPage(LOGIN_URL + "?FROM" + request.getURI().getPath(),exchange);
        }

        //增强
        request.mutate().header("Authorization","Bearer "+jwt);
        return chain.filter(exchange);
    }

    private Mono<Void> toLoginPage(String loginUrl, ServerWebExchange exchange) {

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
